package dian.qing.li.demo.security.exception;

import dian.qing.li.demo.security.commons.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @program: seedland-uuc
 * @description: 全局错误异常
 * @author: EC_liqingdian
 * @create: 2020-03-22 21:56
 **/
@Slf4j
@RestController
@RequestMapping(value = {"${server.error.path:${error.path:/error}}"}, name = "ERROR")
public class GlobalErrorHandler implements ErrorController {
    private static final String PATH = "error";

    @Autowired
    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return PATH;
    }

    /**
     * "timestamp": "2020-03-22 21:50:50",
     * "status": 500,
     * "error": "Internal Server Error",
     * "message": "Invalid mime type \"applic\": does not contain '/'",
     * "path": "/api/v1/test2"
     * EC_liqingdian
     */
    @RequestMapping
    public RestResult handle(HttpServletRequest request) {
        WebRequest webRequest = new ServletWebRequest(request);
        Map<String, Object> errorAttributes = this.errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults());
        int status = Integer.valueOf(errorAttributes.get("status").toString());
        Object error = errorAttributes.get("error");
        String message = errorAttributes.get("message") == null ? "" : errorAttributes.get("message").toString();
        Object url = errorAttributes.get("path");
        log.error("\n请求路径:\n{}\n异常:{}\n异常信息:{}", url, error, message);
        if (StringUtils.isNotBlank(message)) {
            if (StringUtils.equals(message, HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())) {
                return RestResult.failed(HttpStatus.INTERNAL_SERVER_ERROR.value(), message, null);
            } else {
                return RestResult.failed(message);
            }
        }
        return RestResult.failed(status, error.toString(), null);
    }
}
